﻿using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace NewtifyMe.ParseFeeds
{

    public static class XmlReaderManager
    {

        public static List<RssFeedItem> GetListItens(String url)
        {

            List<RssFeedItem> list = new List<RssFeedItem>();
          
            XmlDocument RSSXml = new XmlDocument();
            RSSXml.Load(url);
  
            XmlNodeList RSSNodeList = RSSXml.SelectNodes("rss/channel/item");

            StringBuilder sb = new StringBuilder();
            foreach (XmlNode RSSNode in RSSNodeList)
            {
                XmlNode RSSSubNode;
                RSSSubNode = RSSNode.SelectSingleNode("title");
                string title = RSSSubNode != null ? RSSSubNode.InnerText : "";
                RSSSubNode = RSSNode.SelectSingleNode("link");
                string link = RSSSubNode != null ? RSSSubNode.InnerText : "";
                RSSSubNode = RSSNode.SelectSingleNode("description");
                string desc = RSSSubNode != null ? RSSSubNode.InnerText : "";

                RSSSubNode = RSSNode.SelectSingleNode("pubDate");
                SqlDateTime datetime = RSSSubNode != null ? Convert.ToDateTime(RSSSubNode.InnerText.ToString()) : SqlDateTime.Null;

                XmlNodeList cats = RSSNode.SelectNodes("category");
                String categories = "";
                foreach (XmlNode RSSNodeCat in cats)
                {
                    categories +=  
                    RSSNodeCat.InnerText + " : ";
                }


                list.Add(new RssFeedItem()
                             {
                                 Title = title,
                                 Description = desc,
                                 Link = link,
                                 PublishDate =datetime.IsNull ? "" : datetime.Value.ToString(),
                                 Categorys = categories

                             });

            }

            return list;
        }

    }
}

